<?php
namespace app\index\controller;

use app\admin\model\test\dyzn\Cate as dyznCate;
use app\admin\model\test\dyzn\Subject as dyznSubject;
use app\admin\model\test\hld\Cate as hldCate;
use app\admin\model\test\hld\Subject as hldSubject;
use app\admin\model\test\mbti\Cate as mbtiCate;
use app\admin\model\test\zym\Subject as zymSubject;
use app\admin\model\test\mbti\Subject as mbtiSubject;
use app\admin\model\test\zym\Cate as zymCate;
use app\common\controller\Frontend;
use app\common\model\TestDyznAnswer;
use app\common\model\TestMbtiAnswer;
use app\common\model\TestZymAnswer;
use app\common\model\TestHldAnswer;
use app\common\model\Course;
use think\Config;
use think\Cookie;
use think\Hook;
use think\Db;
use think\Session;
use think\Validate;
use think\Request;
use app\admin\model\User;
use fast\Random;
use app\common\model\Download;    //下载方法公共类
/**
 * 测试中心
 */
class Testing extends Frontend
{
    protected $noNeedRight = '*';
    protected $testConfig;
    protected $noNeedLogin = ['dyzntestreport','zymtestreport','mbtitestreport','hldtestreport','saveimg'];
    protected $testOrder = ['hld','mbti','dyzn','zym'];
    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $uid = input('uid');
        if(!$uid){
            $uid = $this -> auth -> id;
        }
        $this -> assignconfig('uid',$uid);
        $this-> testConfig = config('site.test');
        $this -> assign('from',input('from') ? input('from') : '');
    }

    public function dyzntest(){
        $isExt = TestDyznAnswer::get(['user_id'=>$this -> auth -> id]);
        if($isExt){
            $this -> redirect('dyzntestreport');
//            $this -> success('您已经测试完毕！','/index');
        }

        $subjects = (new dyznSubject) -> order('sort asc') -> select();
        $count = count($subjects);

        if($this -> request -> isAjax() && $this -> request -> isPost()){
            $answers = explode('-',trim($this -> request -> post('answers'),'-'));
            $as = [];
            foreach ($answers as $k => $v){
                $a = explode(':',$v);
                if($a[0] && $a[1]){
                    $as[$a[0]] = $a[1];
                }

            }

            unset($v);
            $cv = [];
            foreach ($subjects as $k => $v){
                if(!isset($as[$v -> id])) continue;
                if(isset($cv[$v->getData('cate_id')])){
                    $cv[$v->getData('cate_id')] += $this -> getDyznScore($as[$v->id]);
                }else{
                    $cv[$v->getData('cate_id')] = $this -> getDyznScore($as[$v->id]);
                }
            }

            $data = [
                'user_id'   => $this -> auth -> id,
                'answers'   => serialize($as),
                'answers_ana'   => serialize($cv)
            ];
            $re = (new TestDyznAnswer) -> save($data);
            if($re){
                $this -> success();
            }else{
                $this -> error();
            }
        }

        $this -> assignconfig('count',$count);
        $this -> assign('count',$count);
        $this -> assign('subjects',$subjects);
        return $this->view->fetch();
    }

    public function dyzntestreport(){
        $this -> view -> engine -> layout("layout/testing");
        $uid = input('uid');
        $from = input('from');
        if(!$uid){
            $uid = $this -> auth -> id;
        }

        $fromAdmin = !is_null($from) && $from == 'admin' ? 1 : 0 ;

        $cates = dyznCate::all();
        $row = TestDyznAnswer::get(['user_id'=>$uid]);
        if(!$row){
            $this -> redirect('dyzntest');
//            $this -> success('您已经测试完毕！','/index');
        }
        $answers_ana = unserialize($row->answers_ana);
        rsort($answers_ana);
        foreach ($answers_ana as $k => $v){
            $a = $v*4;
            $answers_ana[$k] = $a;
        }
        $assData = [
            'cates' => $cates,
            'answers_ana'   =>  $answers_ana
        ];
//        halt($answers_ana);
        $this -> assign('imgs',unserialize($row -> imgs));
        $this -> assign('fromAdmin',$fromAdmin);
        $this -> assign('assData',$assData);
        $this -> assign('row',$row);
        $this -> assignconfig('assData',$assData);
        return $this -> fetch();
    }

    private function getDyznScore($answer){
        switch ($answer){
            case 'A':
                return 5;
            case 'B':
                return 4;
            case 'C':
                return 3;
            case 'D':
                return 2;
            case 'E':
                return 1;
        }
    }

    public function zymtest(){
        $isExt = TestZymAnswer::get(['user_id'=>$this -> auth -> id]);
        if($isExt){
            $this -> redirect('zymtestreport');
//            $this -> success('您已经测试完毕！','/index');
        }

        $subjects = (new zymSubject()) -> order('sort asc') -> select();
        $count = count($subjects);

        if($this -> request -> isAjax() && $this -> request -> isPost()){
            $answers = explode('-',trim($this -> request -> post('answers'),'-'));
            $as = [];
            foreach ($answers as $k => $v){
                $a = explode(':',$v);
                if($a[0] && $a[1]){
                    $as[$a[0]] = $a[1];
                }
            }
            unset($v);
            $cv = [];
            foreach ($subjects as $k => $v){
                if(!isset($as[$v -> id])) continue;
                if(isset($cv[$v->getData('cate_id')])){
                    $cv[$v->getData('cate_id')] += $as[$v->id];
                }else{
                    $cv[$v->getData('cate_id')] = $as[$v->id];
                }
            }

            $data = [
                'user_id'   => $this -> auth -> id,
                'answers'   => serialize($as),
                'answers_ana'   => serialize($cv)
            ];
            $re = (new TestZymAnswer()) -> save($data);
            if($re){
                $this -> success();
            }else{
                $this -> error();
            }
        }

        $this -> assignconfig('count',$count);
        $this -> assign('count',$count);
        $this -> assign('subjects',$subjects);
        return $this->view->fetch();
    }

    public function zymtestreport(){
         $this -> view -> engine -> layout("layout/testing");
        $uid = input('uid');
        $from = input('from');
        if(!$uid){
            $uid = $this -> auth -> id;
        }

        $fromAdmin = !is_null($from) && $from == 'admin' ? 1 : 0 ;

        $cates = zymCate::all();
        $row = TestZymAnswer::get(['user_id'=>$uid]);

        if(!$row){
            $this -> redirect('zymtest');
        }
        $answers_ana = unserialize($row->answers_ana);
        arsort($answers_ana); // 降序排序
        $largestFour = array_slice($answers_ana, 0, 1,true); // 获取最大的值
        $assData = [
            'cates' => $cates,
            'answers_ana'   => $answers_ana,
            'answers_ana_max'   => max($largestFour)+5
        ];

        $this -> assign('fromAdmin',$fromAdmin);
        $this -> assign('assData',$assData);
        $this -> assignconfig('assData',$assData);
        $this -> assign('row',$row);
        return $this -> fetch();
    }

    public function mbtitest(){
        $isExt = TestMbtiAnswer::get(['user_id'=>$this -> auth -> id]);
        if($isExt){
            $this -> redirect('mbtitestreport');
//            $this -> success('您已经测试完毕！','/index');
        }

        $subjects = (new mbtiSubject()) -> order('sort asc') -> select();
        $count = count($subjects);

        if($this -> request -> isAjax() && $this -> request -> isPost()){
            $answers = explode('-',trim($this -> request -> post('answers'),'-'));
            // $as = [];
            // foreach ($answers as $k => $v){
            //     $as[$v['id']] = ['a'=>$v['A'],'b'=>$v['B']];
            // }
            $as = [];
            foreach ($answers as $k => $v){
                $a = explode(':',$v);
                if($a[0]+1 && $a[1]){
                    $as[$a[0]+1] = $a[1];
                }
            }
            unset($v);
            $cv = [];
            foreach ($as as $k => $v){
                $info = (new mbtiSubject()) -> where('sort',$k) -> find();

                if(isset($v)){
                    $cv[strtolower($info['a_cname'])]=
                    isset($cv[strtolower($info['a_cname'])])?bcadd($v,$cv[strtolower($info['a_cname'])]):$v;

                    $b = bcsub(5,$v);
                    $cv[strtolower($info['b_cname'])]=
                    isset($cv[strtolower($info['b_cname'])])?bcadd($b,$cv[strtolower($info['b_cname'])]):$b;

                }
                // if($v['a']>0){
                //     $cv[strtolower($info['a_cname'])]=
                //     isset($cv[strtolower($info['a_cname'])])?bcadd($v['a'],$cv[strtolower($info['a_cname'])]):$v['a'];
                // }
                // if($v['b']>0){
                //     $cv[strtolower($info['b_cname'])]=
                //     isset($cv[strtolower($info['b_cname'])])?bcadd($v['b'],$cv[strtolower($info['b_cname'])]):$v['b'];
                // }
            }
            $data = [
                'user_id'   => $this -> auth -> id,
                'user_nickname'   => $this -> auth -> nickname,
                'user_mobile'   => $this -> auth -> mobile,
                'answers'   => serialize($as),
                'answers_ana'   => serialize($cv)
            ];
            $re = (new TestMbtiAnswer()) -> save($data);
            if($re){
                $this -> success();
            }else{
                $this -> error();
            }
        }

        $this -> assignconfig('count',$count);
        $this -> assign('count',$count);
        
        $this -> assign('subjects',$subjects);
        return $this->view->fetch();
    }

    public function mbtitestreport(){
        $this -> view -> engine -> layout("layout/testing");
        $uid = input('uid');
        $from = input('from');
        if(!$uid){
            $uid = $this -> auth -> id;
        }

        $fromAdmin = !is_null($from) && $from == 'admin' ? 1 : 0 ;
        $row = TestMbtiAnswer::get(['user_id'=>$uid]);
        $cates = mbtiCate::all();
        $cs = [];
        $models = [];
        foreach ($cates as $k => $v){
            $cs[$v['cate']] = $v['desc'];
            $models[$v['cate']] = $v['models'];
        }
        if(!$row){
            $this -> redirect('mbtitest');
        }
        $answers_ana = unserialize($row->answers_ana);

        $ae = isset($answers_ana['e']) ? $answers_ana['e'] : 0;
        $ai = isset($answers_ana['i']) ? $answers_ana['i'] : 0;
        $an = isset($answers_ana['n']) ? $answers_ana['n'] : 0;
        $as = isset($answers_ana['s']) ? $answers_ana['s'] : 0;
        $at = isset($answers_ana['t']) ? $answers_ana['t'] : 0;
        $af = isset($answers_ana['f']) ? $answers_ana['f'] : 0;
        $aj = isset($answers_ana['j']) ? $answers_ana['j'] : 0;
        $ap = isset($answers_ana['p']) ? $answers_ana['p'] : 0;

        $e = [
            'type'=>'e',
            'count' => $ae>9? 9: $ae,
            'percent'   => round($ae/($ae+$ai),2),
            'name'  => '外向',
            'names'  => '外向(E)'
        ];
        $i = [
            'type'=>'i',
            'count' => $ai>9? 9: $ai,
            'percent'   => 1- $e['percent'],
            'name'  => '内向',
            'names'  => '内向(I)'
        ];
        $n = [
            'type'=>'n',
            'count' => $an>9? 9: $an,
            'percent'   => round($an/($an+$as),2),
            'name'  => '直觉',
            'names'  => '直觉(N)',
        ];
        $s = [
            'type'=>'s',
            'count' => $as>9? 9: $as,
            'percent'   => 1-$n['percent'],
            'name'  => '感觉',
            'names'  => '感觉(S)',
        ];
        $t = [
            'type'=>'t',
            'count' => $at>9? 9: $at,
            'percent'   => round($at/($at+$af),2),
            'name'  => '思考',
            'names'  => '思考(T)',
        ];
        $f = [
            'type'=>'f',
            'count' => $af>9? 9: $af,
            'percent'   => 1-$t['percent'],
            'name'  => '情感',
            'names'  => '情感(F)',
        ];
        $j = [
            'type'=>'j',
            'count' => $aj>9? 9: $aj,
            'percent'   => round($aj/($aj+$ap),2),
            'name'  => '判断',
            'names'  => '判断(J)'
        ];
        $p = [
            'type'=>'p',
            'count' => $ap>9? 9: $ap,
            'percent'   => 1 - $j['percent'],
            'name'  => '感知',
            'names'  => '感知(P)'
        ];

        $str = '';
        if($ai>=$ae){
            $str .= 'i';
        }else{
            $str .= 'e';
        }
        if($an>=$as){
            $str .= 'n';
        }else{
            $str .= 's';
        }

        if($af>=$at){
            $str .= 'f';
        }else{
            $str .= 't';
        }

        if($ap>=$aj){
            $str .= 'p';
        }else{
            $str .= 'j';
        }

        $retArr = [
            'e' => $e,
            'i' => $i,
            'n' => $n,
            's' => $s,
            'j' => $j,
            'p' => $p,
            'f' => $f,
            't' => $t
        ];
        $retArr1 = [
            $e, $i, $n, $s, $j, $p, $f, $t
        ];
//        echo "<pre>";
//        print_r($retArr);
        $vaccineCount = array_column($retArr1, 'count');
        array_multisort($vaccineCount ,SORT_DESC,$retArr1);
        $largestFour = array_slice($retArr1, 0, 1,true); // 获取最大的值

        $this -> assign('models',$models);
        $this -> assignconfig('ret_arr',$retArr);
        $this -> assignconfig('ret_arr_max',max(array_column($largestFour, 'count'))+5);
        $this -> assign('ret_arr',$retArr);
        $this -> assign('ret',$str);
        $this -> assign('cates',$cs);
        $this -> assign('fromAdmin',$fromAdmin);
//        $assData = [
//            'cates' => $cates,
//            'answers_ana'   => $answers_ana
//        ];
//        $this -> assign('assData',$assData);
        $this -> assignconfig('assData',$retArr1);
        $this -> assign('row',$row);
        return $this -> fetch();
    }

    public function hldtest(){
        $isExt = TestHldAnswer::get(['user_id'=>$this -> auth -> id]);
        if($isExt){
           $this -> redirect('hldtestreport');
            // $this -> success('您已经测试完毕!','/index');
        }

        $subjects = (new hldSubject()) -> order('sort asc') -> select();
        $count = count($subjects);

        if($this -> request -> isAjax() && $this -> request -> isPost()){
            $answers = explode('-',trim($this -> request -> post('answers'),'-'));
            $as = [];
            foreach ($answers as $k => $v){
                $a = explode(':',$v);
                if($a[0] && $a[1]){
                    $as[$a[0]] = $a[1];
                }
            }
            unset($v);

            $bs = [];
            foreach($subjects as $K => $v){
                $bs[$v['id']] = $v;
            }
            unset($v);

            $cv = [];
            foreach ($as as $k => $v){
                $row = $bs[$k];
                if($v == 'a'){
                    if(isset($cv[$row -> getData('cate_2')])){
                        ++$cv[$row -> getData('cate_2')];
                    }else{
                        $cv[$row -> getData('cate_2')] = 1;
                    }
                }
            }
            $data = [
                'user_id'   => $this -> auth -> id,
                'answers'   => serialize($as),
                'answers_ana'   => serialize($cv)
            ];

            $re = (new TestHldAnswer()) -> save($data);
            if($re){
                $this -> success();
            }else{
                $this -> error();
            }
        }

        $this -> assignconfig('count',$count);
        $this -> assign('count',$count);
        $this -> assign('subjects',$subjects);
        return $this->view->fetch();
    }

    public function hldtestreport(){
        $this -> view -> engine -> layout("layout/testing");
        $uid = input('uid');
        $from = input('from');
        if(!$uid){
            $uid = $this -> auth -> id;
        }

        $fromAdmin = !is_null($from) && $from == 'admin' ? 1 : 0 ;

        $row = TestHldAnswer::get(['user_id'=>$uid]);

        if(!$row){
            $this -> redirect('hldtest');
        }
        $answers_ana = unserialize($row->answers_ana);
        arsort($answers_ana);
        $r = array_slice($answers_ana,0,3);
        $str = '';
        foreach ($r as $k => $v){
            $str .= $k;
        }

        $cates = hldCate::all();
        $cs = [];
        foreach ($cates as $k => $v){
            $cs[$v['cate']] = $v['desc'];
        }

        $this -> assign('cs',$cs);
        $this -> assign('r',$str);


        $this -> assign('assData',$answers_ana);
        // $arr = ['现实型 ( R )','常规型 ( C )','企业型 ( E )','社会型 ( S )','艺术型 ( A )','研究型 ( I )'];
        $arr = ['r'=>'现实型 ( R )','c'=>'常规型 ( C )','e'=>'企业型 ( E )','s'=>'社会型 ( S )','a'=>'艺术型 ( A )','i'=>'研究型 ( I )'];
        // $arr = ['r','c','e','s','a','i'];

        $a = unserialize($row -> answers_ana);
        arsort($a); // 降序排序
        $largestFour = array_slice($a, 0, 1,true); // 获取最大的值
        $ana = [];
        foreach ($arr as $k => $value){
            $ana[$value] = isset($a[$k])?$a[$k]:0;
        }
        $this -> assign('fromAdmin',$fromAdmin);
        $this -> assign('row',$row);
        $this -> assignconfig('assData',$ana);
        $this -> assignconfig('assDataMax',max($largestFour)+5);
        return $this -> fetch();
    }


    public function saveimg(){
        if($this -> request -> isAjax() && $this -> request -> isPost()){
            $data = $this -> request -> post();
            switch ($data['type']){
                case 'Dyzn' :
                    $model = new TestDyznAnswer();
                    break;
                case 'Mbti':
                    $model = new TestMbtiAnswer();
                    break;
                case 'Hld':
                    $model = new TestHldAnswer();
                    break;
                case 'Zym':
                    $model = new TestZymAnswer();
                    break;
            }

            if(!$this -> auth -> id && !$data['uid']){
                $this -> error('请登录');
            }

            $uid = $data['uid'] ? $data['uid'] : $this -> auth -> id;

            $row = $model -> where(['user_id' => $uid]) -> find();

            if(!$row){
                $this -> error('失败');
            }

            $img = [];
            if(is_array($data['baseimg'])){
                foreach ($data['baseimg'] as $k => $picInfo){
                    $re = $this -> fnsaveimg($picInfo);
                    if($re){
                        $img[] = $re;
                    }
                }
            }else{
                $re = $this -> fnsaveimg($data['baseimg']);
                if($re){
                    $img[] = $re;
                }
            }

            $row -> imgs = serialize($img);
            $row -> save();
            if($row -> imgs){
                $this -> success('成功');
            }

        }
    }

    private function fnsaveimg($picInfo){
        $streamFileRand = date('YmdHis').rand(1000,9999); //图片名
        $picType ='.png';//图片后缀
        $streamFilename =  $_SERVER['DOCUMENT_ROOT'] . "/echarts_img/".$streamFileRand .$picType; //图片保存地址
        preg_match('/(?<=base64,)[\S|\s]+/',$picInfo,$picInfoW);//处理base64文本
        $re = file_put_contents($streamFilename,base64_decode($picInfoW[0]));//文件写入
        if($re){
            return "/echarts_img/".$streamFileRand .$picType;
        }else{
            return false;
        }
    }


    public function next(){
        $current = input('current') ? input('current') : 'hld';
        $next = '';
        foreach ($this -> testOrder as $k => $test){
            $ext = Db::name('test_'.$test.'_answer') -> where(['user_id' => $this -> auth -> id]) -> find();
            if(!$ext){
                $next = 'testing/'.$test.'test';
                break;
            }
        }

        if($next == ''){
            foreach ($this -> testOrder as $k => $test){
                if($current == $test){
                    $s = next($this -> testOrder);
                    if($s){
                        $next = 'testing/'.$s.'test';
                    }else{
                        $next = 'testing/hldtest';
                    }
                }
                next($this -> testOrder);
            }
        }
        $this -> redirect($next);
    }

    //统一测评
    public function vocation(){
        ini_set('max_input_vars','10000');
        $user = new User();
        $this -> view -> engine -> layout("layout/testing");
         // 霍兰德
         $isExt = TestHldAnswer::get(['user_id'=>$this -> auth -> id]);
         // 多元智能
         $isDyzn = TestDyznAnswer::get(['user_id'=>$this -> auth -> id]);
         // 职业锚
         $isZym = TestZymAnswer::get(['user_id'=>$this -> auth -> id]);
         // MBTI
         $isMbti = TestMbtiAnswer::get(['user_id'=>$this -> auth -> id]);
         if($isExt && $isDyzn && $isZym && $isMbti){ //跳转到结果页面
             $this -> redirect('vocation_report');
             die();
         }
        // 霍兰德
        $subjects1 = (new hldSubject()) -> order('id asc') -> select();
        //多元智能
        $subjects2 = (new dyznSubject)-> order('id asc')-> select();
        // MBTI
        $subjects3 = (new mbtiSubject()) -> order('id asc') -> select();
        // 职业锚
        $subjects4 = (new zymSubject()) -> order('id asc') -> select();
        $subjects = array_merge($subjects1,$subjects2,$subjects3,$subjects4);

        $count = count($subjects);
        if($this -> request -> isAjax() && $this -> request -> isPost()){
            $answers = $this -> request -> post('answer_arr/a');
            //霍兰德结果
            $answers1 = $answers[1];
            $answers2 = $answers[2];
            $answers3 = $answers[3];
            $answers4 = $answers[4];
            $answers1_kexin = 0;
            $answers2_kexin = 0;
            $answers3_kexin = 0;
            $answers4_kexin = 0;
            $kexin = [];
            if($answers1)
            {
                $as = [];
                foreach ($answers1 as $k => $v){
                    // $a = explode(':',$v);
                    // if($a[0] && $a[1]){
                    if($v['id']==121) continue;
                    $as[$k] = $v['answer'];
                    // }
                    //判断霍兰德 可信度
                    if($v['id']==$answers2[41]['sort']){
//                        echo "霍兰德".$answers2[41]['sort']."答案：".$v['answer']."<br/>";
//                        echo "霍兰德".$answers2[41]['sort']."二次答案：".$answers2[41]['answer']."<br/>";
                        if($answers2[41]['answer']==$v['answer']){
                            $answers1_kexin = 25;
                        }
                        $kexin[1] = [
                            'id' => $v['id'],
                            'answer' => $v['answer'],
                            'new_answer' => $answers2[41]['answer'],
                        ];
                    }
                }
                unset($v);
                $bs = [];
                foreach($subjects1 as $K => $v){
                    if($v['id']==121) continue;
                    $bs[$v['id']] = $v;
                }
                unset($v);

                $cv = [];
                foreach ($as as $k => $v){
                    $row = $bs[$k];
                    if($v == 'a'){
                        if(isset($cv[$row -> getData('cate_2')])){
                            ++$cv[$row -> getData('cate_2')];
                        }else{
                            $cv[$row -> getData('cate_2')] = 1;
                        }
                    }
                }
                $data = [
                    'user_id'   => $this -> auth -> id,
                    'answers'   => serialize($as),
                    'answers_ana'   => serialize($cv),
                ];
                $re = (new TestHldAnswer()) -> save($data);
            }
//            echo "霍兰德可信度".$answers1_kexin."<br/>";

            //多元智能 结果
            if($answers2)
            {
                $as = [];
                foreach ($answers2 as $k => $v){
                    if($v['id']==41) continue;
                    $as[$k] = $v['answer'];

                    //多元智能 可信度
                    if($v['id']==$answers3[154]['sort']){
//                        echo "多元智能".$answers3[154]['sort']."答案：".$v['answer']."<br/>";
//                        echo "多元智能".$answers3[154]['sort']."二次答案：".$answers3[154]['answer']."<br/>";
                        if($answers3[154]['answer']==$v['answer']){
                            $answers2_kexin = 25;
                        }
                        $kexin[2] = [
                            'id' => $v['id'],
                            'answer' => $v['answer'],
                            'new_answer' => $answers3[154]['answer'],
                        ];
                    }
                }
                unset($v);
                $cv = [];
                foreach ($subjects2 as $k => $v)
                {
                    if(!isset($as[$v -> id])) continue;
                    if($v['id']==41) continue;
                    if(isset($cv[$v->getData('cate_id')])){
                        $cv[$v->getData('cate_id')] += $this -> getDyznScore($as[$v->id]);
                    }else{
                        $cv[$v->getData('cate_id')] = $this -> getDyznScore($as[$v->id]);
                    }
                }
                $data = [
                    'user_id'   => $this -> auth -> id,
                    'answers'   => serialize($as),
                    'answers_ana'   => serialize($cv),
                ];
                $re = (new TestDyznAnswer()) -> save($data);
            }

//            echo "多元智能可信度".$answers2_kexin."<br/>";


            //MBTI 结果
            if($answers3)
            {
                $as = [];
                foreach ($answers3 as $k => $vv){
                    if($vv['id']==154) continue;
                    if(isset($vv['answer']))
                        $as[$k] = $vv['answer'];

                    //判断mbti 可信度
                    if($vv['id']==$answers4[41]['sort']){
//                        echo "MBTI".$answers4[41]['sort']."答案：".$vv['answer']."<br/>";
//                        echo "MBTI".$answers4[41]['sort']."二次答案：".$answers4[41]['answer']."<br/>";
                        if($answers4[41]['answer']==$vv['answer']){
                            $answers3_kexin = 25;
                        }
                        $kexin[3] = [
                            'id' => $vv['id'],
                            'answer' => $vv['answer'],
                            'new_answer' => $answers4[41]['answer'],
                        ];
                    }
                }
                unset($v);
                $cv = [];
                foreach ($as as $k => $v){
                    $cv[$v] = isset($cv[$v]) ? ++$cv[$v]:1;
                }
                $data = [
                    'user_id'   => $this -> auth -> id,
                    'answers'   => serialize($as),
                    'answers_ana'   => serialize($cv),
                ];
                $re = (new TestMbtiAnswer()) -> save($data);
            }
//            echo "MBTI".$answers3_kexin."<br/>";

            //职业锚
            if($answers4){
                $as = [];
                foreach ($answers4 as $k => $v){
                    if($v['id']==41) continue;
                    $as[$k] = $v['answer'];
                    //判断职业锚可信度
                    if($v['id']==$answers1[121]['sort']){
//                        echo "职业锚id".$answers1[121]['sort']."答题id：".$v['id']."<br/>";
//                        echo "职业锚".$answers1[121]['sort']."答案：".$v['answer']."<br/>";
//                        echo "职业锚".$answers1[121]['sort']."二次答案：".$answers1[121]['answer']."<br/>";
                        if($answers1[121]['answer']==$v['answer']){
                            $answers4_kexin = 25;
                        }

                        $kexin[4] = [
                            'id' => $v['id'],
                            'answer' => $v['answer'],
                            'new_answer' => $answers1[121]['answer'],
                        ];
                    }
                }
                unset($v);
                $cv = [];
                foreach ($subjects4 as $k => $v)
                {
                    if(!isset($as[$v -> id])) continue;
                    if($v['id']==41) continue;
                    if(isset($cv[$v->getData('cate_id')])){
                        $cv[$v->getData('cate_id')] += $as[$v->id];
                    }else{
                        $cv[$v->getData('cate_id')] = $as[$v->id];
                    }
                }
                $data = [
                    'user_id'   => $this -> auth -> id,
                    'answers'   => serialize($as),
                    'answers_ana'   => serialize($cv),
                ];
                $re = (new TestZymAnswer()) -> save($data);
            }
//            echo "职业锚".$answers4_kexin."<br/>";
            $answers_kexin =  $answers1_kexin+$answers2_kexin+$answers3_kexin+$answers4_kexin;
            Db::name('user')->where(['id'=>$this->auth->id])->update(['reliability'=>$answers_kexin,'reliability_text'=>json_encode($kexin)]);
            $this -> success();
        }

        $this -> assignconfig('count',$count);
        $this -> assign('count',$count);
        $this -> assign('subjects',$subjects);
        return $this->view->fetch();
    }

    public function vocation_report(){
        // 霍兰德
        $isExt = TestHldAnswer::get(['user_id'=>$this -> auth -> id]);
        // 多元智能
        $isDyzn = TestDyznAnswer::get(['user_id'=>$this -> auth -> id]);
        // 职业锚
        $isZym = TestZymAnswer::get(['user_id'=>$this -> auth -> id]);
        // MBTI
        $isMbti = TestMbtiAnswer::get(['user_id'=>$this -> auth -> id]);

        if(!$isExt && !$isDyzn && !$isZym && !$isMbti){ //跳转到结果页面
            $this -> redirect('vocation');
        }

        $uid = input('uid');
        $from = input('from');
        if(!$uid){
            $uid = $this -> auth -> id;
        }
        $this -> view -> engine -> layout("layout/testing");
        $fromAdmin = !is_null($from) && $from == 'admin' ? 1 : 0 ;

        $row = TestHldAnswer::get(['user_id'=>$uid]);
        $answers_ana = unserialize($row->answers_ana);
        arsort($answers_ana);
        $r = array_slice($answers_ana,0,3);
        $str = '';
        foreach ($r as $k => $v){
            $str .= $k;
        }
        $cates = hldCate::all();
        $cs = [];
        foreach ($cates as $k => $v){
            $cs[$v['cate']] = $v['desc'];
        }

        // $arr = ['r','c','e','s','a','i'];
        $arr = ['r'=>'现实型 ( R )','c'=>'常规型 ( C )','e'=>'企业型 ( E )','s'=>'社会型 ( S )','a'=>'艺术型 ( A )','i'=>'研究型 ( I )'];

        $a = unserialize($row -> answers_ana);
        arsort($a); // 降序排序
        $largestFour2 = array_slice($a, 0, 1,true); // 获取最大的值
        $ana = [];
        foreach ($arr as $v => $value){
            $ana[$value] = isset($a[$v])?$a[$v]:0;
        }
        $this -> assign('fromAdmin',$fromAdmin);
        $this -> assignconfig('assData',$ana);
        $this -> assignconfig('assDataMax',max($largestFour2)+5);
        $this -> assignconfig('testConfig',$this-> testConfig);

        //多元智能
        $cates1 = dyznCate::all();
        $row1 = TestDyznAnswer::get(['user_id'=>$uid]);
        $answers_ana1 = unserialize($row1->answers_ana);
        foreach ($answers_ana1 as $k => $v){
            $a = $v*4;
            $answers_ana1[$k] = $a;
        }
        $assData1 = [
            'cates' => $cates1,
            'answers_ana'   => $answers_ana1
        ];
        $this -> assignconfig('assData1',$assData1);



        //MBTI
        $row2 = TestMbtiAnswer::get(['user_id'=>$uid]);
        $cates2 = mbtiCate::all();
        $cs2 = [];
        foreach ($cates2 as $k => $v){
            $cs2[$v['cate']] = $v['desc'];
        }
        $answers_ana2 = unserialize($row2->answers_ana);

        $ae = isset($answers_ana2['e']) ? $answers_ana2['e'] : 0;
        $ai = isset($answers_ana2['i']) ? $answers_ana2['i'] : 0;
        $an = isset($answers_ana2['n']) ? $answers_ana2['n'] : 0;
        $as = isset($answers_ana2['s']) ? $answers_ana2['s'] : 0;
        $at = isset($answers_ana2['t']) ? $answers_ana2['t'] : 0;
        $af = isset($answers_ana2['f']) ? $answers_ana2['f'] : 0;
        $aj = isset($answers_ana2['j']) ? $answers_ana2['j'] : 0;
        $ap = isset($answers_ana2['p']) ? $answers_ana2['p'] : 0;

        $e = [
            'type'=>'e',
            'count' => $ae>9? 9: $ae,
            'percent'   => round($ae/($ae+$ai),2),
            'name'  => '外向',
            'names'  => '外向(E)'
        ];
        $i = [
            'type'=>'i',
            'count' => $ai>9? 9: $ai,
            'percent'   => abs(1- $e['percent']),
            'name'  => '内向',
            'names'  => '内向(I)'
        ];
        $n = [
            'type'=>'n',
            'count' => $an>9? 9: $an,
            'percent'   => round($an/($an+$as),2),
            'name'  => '直觉',
            'names'  => '直觉(N)',
        ];
        $s = [
            'type'=>'s',
            'count' => $as>9? 9: $as,
            'percent'   => abs(1-$n['percent']),
            'name'  => '感觉',
            'names'  => '感觉(S)',
        ];
        $t = [
            'type'=>'t',
            'count' => $at>9? 9: $at,
            'percent'   => round($at/($at+$af),2),
            'name'  => '思考',
            'names'  => '思考(T)',
        ];
        $f = [
            'type'=>'f',
            'count' => $af>9? 9: $af,
            'percent'   => abs(1-$t['percent']),
            'name'  => '情感',
            'names'  => '情感(F)',
        ];
        $j = [
            'type'=>'j',
            'count' => $aj>9? 9: $aj,
            'percent'   => round($aj/($aj+$ap),2),
            'name'  => '判断',
            'names'  => '判断(J)'
        ];
        $p = [
            'type'=>'p',
            'count' => $ap>9? 9: $ap,
            'percent'   => abs(1 - $j['percent']),
            'name'  => '感知',
            'names'  => '感知(P)'
        ];
        $str = '';
        if($ai>=$ae){
            $str .= 'i';
        }else{
            $str .= 'e';
        }
        if($an>=$as){
            $str .= 'n';
        }else{
            $str .= 's';
        }

        if($af>=$at){
            $str .= 'f';
        }else{
            $str .= 't';
        }

        if($ap>=$aj){
            $str .= 'p';
        }else{
            $str .= 'j';
        }
        $retArr = [
            'e' => $e,
            'i' => $i,
            'n' => $n,
            's' => $s,
            'j' => $j,
            'p' => $p,
            'f' => $f,
            't' => $t
        ];
        $vaccineCount = array_column($retArr, 'count');
        array_multisort($vaccineCount ,SORT_DESC,$retArr);
        $largestFour1 = array_slice($retArr, 0, 1,true); // 获取最大的值

        $this -> assignconfig('ret_arr',$retArr);
        $this -> assignconfig('ret_arr_max',max(array_column($largestFour1, 'count'))+5);

        //职业锚
        $cates3 = zymCate::all();
        $row3 = TestZymAnswer::get(['user_id'=>$uid]);

        $answers_ana3 = unserialize($row3->answers_ana);
        arsort($answers_ana3); // 降序排序
        $largestFour = array_slice($answers_ana3, 0, 1,true); // 获取最大的值
        $assData3 = [
            'cates' => $cates3,
            'answers_ana'   => $answers_ana3,
            'answers_ana_max'   => max($largestFour)+5
        ];
        $this -> assignconfig('assData3',$assData3);

        return $this -> fetch('report');
    }

    public function vocation_result($code=null)
    {
        // 霍兰德
        $isExt = TestHldAnswer::get(['user_id'=>$this -> auth -> id,'token'=>$code]);
        // 多元智能
        $isDyzn = TestDyznAnswer::get(['user_id'=>$this -> auth -> id,'token'=>$code]);
        // 职业锚
        $isZym = TestZymAnswer::get(['user_id'=>$this -> auth -> id,'token'=>$code]);
        // MBTI
        $isMbti = TestMbtiAnswer::get(['user_id'=>$this -> auth -> id,'token'=>$code]);

        if(!$isExt && !$isDyzn && !$isZym && !$isMbti){ //跳转到结果页面
            $this -> redirect('vocation');
        }

        $uid = input('uid');
        $from = input('from');
        $this -> view -> engine -> layout("layout/testing");

        $request = Request::instance();
        $domain = $request->domain();

        $hld_img = '';
        if(isset($isExt->imgs)){
            $hld_img = unserialize($isExt->imgs);
            $hld_img = $hld_img[0]? $hld_img[0]:"";
        }

        //表格列表
        $answers_ana = unserialize($isExt->answers_ana);
        arsort($answers_ana);
        $r = array_slice($answers_ana,0,3);
        $str = '';
        foreach ($r as $k => $v){
            $str .= $k;
        }
        $this -> assign('str',strtoupper($str));

        $dyzn_img = '';
        if(isset($isDyzn->imgs)){
            $dyzn_img = unserialize($isDyzn->imgs);
            $dyzn_img = $dyzn_img[0]? $dyzn_img[0]:"";
        }

        $zym_img = '';
        if(isset($isZym->imgs)){
            $zym_img = unserialize($isZym->imgs);
            $zym_img = $zym_img[0]? $zym_img[0]:"";
        }

        $mbti_img = '';
        if(isset($isMbti->imgs)){
            $mbti_img = unserialize($isMbti->imgs);
            $mbti_img = $mbti_img[0]? $mbti_img[0]:"";
        }

        $img_arr = [$hld_img,$dyzn_img,$zym_img,$mbti_img];

        $answers_ana1 = unserialize($isMbti->answers_ana);

        $ae = isset($answers_ana1['e']) ? $answers_ana1['e'] : 0;
        $ai = isset($answers_ana1['i']) ? $answers_ana1['i'] : 0;
        $an = isset($answers_ana1['n']) ? $answers_ana1['n'] : 0;
        $as = isset($answers_ana1['s']) ? $answers_ana1['s'] : 0;
        $at = isset($answers_ana1['t']) ? $answers_ana1['t'] : 0;
        $af = isset($answers_ana1['f']) ? $answers_ana1['f'] : 0;
        $aj = isset($answers_ana1['j']) ? $answers_ana1['j'] : 0;
        $ap = isset($answers_ana1['p']) ? $answers_ana1['p'] : 0;


        $str2 = '';
        if($ai>=$ae){
            $str2 .= 'i';
        }else{
            $str2 .= 'e';
        }
        if($an>=$as){
            $str2 .= 'n';
        }else{
            $str2 .= 's';
        }

        if($af>=$at){
            $str2 .= 'f';
        }else{
            $str2 .= 't';
        }

        if($ap>=$aj){
            $str2 .= 'p';
        }else{
            $str2 .= 'j';
        }
        $this -> assign('str2',strtoupper($str2));


        $this -> assign('img_arr',$img_arr);
        $this -> assign('domain',$domain);
        return $this -> fetch();
    }


}